//
//  OrderViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 2016/10/14.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "OrderViewController.h"
#import "BaseDataRequest.h"
#import "UIImageView+WebCache.h"
#import "OrderDetailViewController.h"
#import "CLUIBaseTableViewController+Empty.h"

@interface OrderViewController ()
@property (strong, nonatomic) NSMutableArray *arrDataSource;
@property (strong, nonatomic) id responseObject;
@property (assign, nonatomic) int page;
@end

@implementation OrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的订单";
    [self showNavgationWithLeftItemWithTitle:@"返回"];
    self.tableView.rowHeight = 82;

    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        if (_arrDataSource.count == 0) {
            weakSelf.page = 1;
        }else{
            weakSelf.page ++;
        }
        [weakSelf requestOrderList];
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    if (self.arrDataSource.count > 0) {
        [_arrDataSource removeAllObjects];
        [self.tableView reloadData];
    }
    self.page = 1;
    [self requestOrderList];
}


#pragma mark - 数据请求
- (void)requestOrderList{
    [SVProgressHUD showWithStatus:@"获取订单信息.." maskType:SVProgressHUDMaskTypeClear];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserToken] forKey:@"token"];
    [dict setObject:[NSString stringWithFormat:@"%d",_page] forKey:@"page"];
    WS(weakSelf);
    [[BaseDataRequest alloc] getOrderLiset:dict WithBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        [self.tableView.footer endRefreshing];
        if ([status isEqualToString:@"0"]) {
            self.responseObject = responseObject;
            NSMutableArray *arrResult = [NSMutableArray arrayWithArray:[responseObject objectForKey:@"result"]];
            [self.arrDataSource addObjectsFromArray:arrResult];
            
            if (arrResult.count == 0 || arrResult.count < 10) {
                if(self.arrDataSource.count == 0){
                    [weakSelf showLabelEmptyCate:CGRectMake((SCREEN_WIDTH - 100)/2, (SCREEN_HEIGHT -140 -64)/2, 100, 100) withTitle:@"这里还没有内容" withImage:[UIImage imageNamed:@"icon_ blank"]];
                    self.tableView.footer.hidden = YES;
                }else{
                    [self.tableView.footer noticeNoMoreData];
                }
            }
            [self.tableView reloadData];
        }else{
            if (self.tableView.footer.isRefreshing) {
                if (self.page>1) {
                    self.page--;
                }
            }
            if(self.arrDataSource.count == 0){
                [weakSelf showLabelEmptyCate:CGRectMake((SCREEN_WIDTH - 100)/2, (SCREEN_HEIGHT -140 -64)/2, 100, 100) withTitle:@"出错了，稍后再试吧" withImage:[UIImage imageNamed:@"icon_wifi"]];
                self.tableView.footer.hidden = YES;
            }else{
                if (error != nil) {
                    TIPSFORVIEW(@"请检测网络设置");
                }else{
                    TIPSFORVIEW([responseObject objectForKey:@"message"]);
                }
            }
        }
    }];
}


#pragma  mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _arrDataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderViewCell" forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OrderViewCell"] ;
    }
    cell.preservesSuperviewLayoutMargins = NO;
    cell.separatorInset = UIEdgeInsetsZero;
    cell.layoutMargins = UIEdgeInsetsZero;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict = _arrDataSource[indexPath.row];
    UIImageView *imageV = [cell.contentView viewWithTag:1];
    [imageV sd_setImageWithURL:[NSURL URLWithString:[dict objectForKey:@"thumb_image"]] placeholderImage:[UIImage imageNamed:@"iocn_default"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        imageV.layer.cornerRadius = 4.0;
        imageV.layer.borderColor = [UIColor grayColor].CGColor;
        imageV.layer.borderWidth = 1.0f;
        imageV.layer.masksToBounds = YES;
    }];
    UILabel *labName = [cell.contentView viewWithTag:2];
    UILabel *labdetail = [cell.contentView viewWithTag:3];
    UILabel *labNumber = [cell.contentView viewWithTag:5];
    UILabel *labTime = [cell.contentView viewWithTag:6];
    UILabel *labStatus = [cell.contentView viewWithTag:4];
    labName.text = [dict objectForKey:@"goodtitle"];
    if ([[dict objectForKey:@"order_type"] isEqualToString:@"1"]) {
        labdetail.text = [NSString stringWithFormat:@"交易金额：%@积分",[dict objectForKey:@"payamount"]];
        labNumber.text = [NSString stringWithFormat:@"交易数量：%@",[dict objectForKey:@"goodscount"]];
        labTime.text = [NSString stringWithFormat:@"交易时间：%@",[dict objectForKey:@"add_time"]];
    }else{
        labdetail.text = [NSString stringWithFormat:@"交易金额：¥ %@",[dict objectForKey:@"payamount"]];
        labNumber.text = [NSString stringWithFormat:@"交易数量：%@",[dict objectForKey:@"goodscount"]];
        labTime.text = [NSString stringWithFormat:@"交易时间：%@",[dict objectForKey:@"add_time"]];
    }
    int index =  [[dict objectForKey:@"status"] intValue] ;
    switch (index) {
        case 0:
            labStatus.text = @"待付款";
            break;
        case 1:
            labStatus.text = @"已付款";
            break;
        case 2:
            labStatus.text = @"已发货";
            break;
        case 3:
            labStatus.text = @"已收货";
            break;
        case 4:
            labStatus.text = @"已取消";
            break;
        default:
            break;
    }
    return cell;
}

#pragma mark - 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dict = _arrDataSource[indexPath.row];
    int index =  [[dict objectForKey:@"status"] intValue] ;
    OrderDetailViewController *orderDetail = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"OrderDetailViewController"];
    orderDetail.strOrderid = [dict objectForKey:@"id"];
    switch (index) {
        case 0:
            orderDetail.orderType = OrderDetailTypePending;
            break;
        case 1:
            orderDetail.orderType = OrderDetailTypePaid;
            break;
        case 2:
            orderDetail.orderType = OrderDetailTypeShip;
            break;
        case 3:
             orderDetail.orderType = OrderDetailTypeComplete;
            break;
        case 4:
            orderDetail.orderType = OrderDetailTypeCancel;
            break;
        default:
            break;
    }
    [self.navigationController pushViewController:orderDetail animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - set/get
- (NSMutableArray *)arrDataSource{
    if (_arrDataSource == nil) {
        _arrDataSource = [NSMutableArray array];
    }
    return _arrDataSource;
}

@end
